package login;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utility.connections;

public class mod_password extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
    public mod_password() {
        super();
    }
    
    public void init(ServletConfig sc)
    {
    	try {
			super.init(sc);
		} catch (ServletException e) {
			e.printStackTrace();
		}
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String user = request.getParameter("user").toString();
		String oldpwd=request.getParameter("oldpwd").toString();
		String newpwd=request.getParameter("newpwd").toString();
		String cnfpwd=request.getParameter("cnfpwd").toString();
		
		String qry="select * from account where username = '" + user + "' and password = '"+oldpwd+"'";
		
		System.out.println("qry (mod_password): " + qry);
		System.out.println("(mod_password) new pwd:"+newpwd);
		System.out.println("(mod_password) cnf pwd:"+cnfpwd);
		ResultSet rsqry;
		try {
			rsqry = connections.getStatement().executeQuery(qry);
		
			if (rsqry.next()==false)
				response.sendRedirect("hom/password_errata.jsp");
			else
			{
				System.out.println("(mod_password) hasnext");
				if(newpwd.equals(cnfpwd)==false)
					response.sendRedirect("hom/password_errata.jsp");
				
				if(cnfpwd.equals(newpwd))
				{
					qry = "update account set password = '"+newpwd+"' where username = '"+user+"'";
					int qryResponse=connections.getStatement().executeUpdate(qry);
					System.out.println("(mod_password:) " + qry);
					System.out.println("(mod_password:) Response " + qryResponse);
					if(qryResponse==1)
						response.sendRedirect("login.jsp");
					else
						response.sendRedirect("ops.jsp");
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
	}

}
